<template>
  <div class="user">
    <div class="top">
    </div>
    <div class="bottom">
      <a-row :gutter="16">
        <a-col :span="24" :md="6"  >
          <a-card  style="width: 100%;position: sticky;top: 80px;margin-bottom: 20px" hoverable >
            <template #cover>

              <div
                  :style="{borderRadius:'5px 5px 0 0', height:'200px', backgroundImage: 'linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(0, 0, 0, 0.5)),url(' + useInfoForm.avatar + ')', 'background-repeat':'no-repeat', backgroundSize:'cover',backgroundPosition:'center center'}"
              ></div>
            </template>
            <a-card-meta :title="useInfoForm.nickName" :description="useInfoForm.sign">
              <template #avatar>
                <a-avatar :size="50" :src="useInfoForm.avatar" />
              </template>
            </a-card-meta>
            <a-row style="text-align: center;margin-top: 15px">
              <a-col :span="8">
                <a-statistic title="关注"  value-style="font-size: 16px;"  :value="articleInfo.followNum"  />
              </a-col>
              <a-col :span="8">
                <a-statistic title="粉丝" value-style="font-size: 16px;" :value="articleInfo.fansNum" />
              </a-col>
              <a-col :span="8">
                <a-statistic  title="文章"  value-style="font-size: 16px;" :value="articleInfo.articleNum" />
              </a-col>
            </a-row>
            <template v-if="isMe"  #actions>
              <a-tooltip placement="top">
                <template #title>
                  后台管理
                </template>
              <setting-outlined  key="setting" />
              </a-tooltip>
              <a-tooltip placement="top">
                <template #title>
                  编辑信息
                </template>
              <edit-outlined  @click="gotoUpdateUserInfo" key="edit" />
              </a-tooltip>
              <a-tooltip placement="top">
                <template #title>
                  退出登录
                </template>
                <LogoutOutlined @click="gotoLogout" key="logout"/>
              </a-tooltip>
            </template>
          </a-card>
        </a-col>
        <a-col :span="24" :md="18">
          <a-row :gutter='8'  >
            <a-col style="margin-bottom: 20px" :xs="24" :sm="12">
              <a-card class="card" size="small" title="解题数量" style="width: 100%">
                <a-row align="middle" :gutter='20'  >
                  <a-col>
                    <a-progress
                        type="circle"
                        :stroke-color="{
                          '0%': '#108ee9',
                          '100%': '#87d068',
                        }"
                        :size="100"
                        :percent="judgePercent"
                    />
                  </a-col>
                  <a-col flex="auto">
                    <a-row v-for="(item,index) in judgeInfo" :key="index" style="margin: 5px 0" :span="24" >
                      <a-col style="position: relative"  :span="24">
                        <a-progress  :percent="percent(item.acNum,item.problemNum)" size="small"  status="active" />
                        <div style="position: absolute;top: -16px;left: 0">
                          <span style="font-size: 12px">{{item.difficultyName}}</span>
                          <span style="font-size: 16px;margin-left: 20px;font-weight: 600">{{item.acNum}}</span>
                          <span style="font-size: 12px;">/{{item.problemNum}}</span>
                        </div>
                      </a-col>
                    </a-row>
                  </a-col>
                </a-row>

              </a-card>
            </a-col>
            <a-col style="margin-bottom: 20px"  :xs="24" :sm="12">
<!--              <a-card class="card" size="small" title="勋章" style="width: 100%">-->
<!--                <a-collapse ghost :bordered="true" v-model:activeKey="activeKey" :expand-icon-position="expandIconPosition">-->
<!--                  <a-collapse-panel :showArrow="false"  key="1" >-->
<!--                    <p>{{ text }}</p>-->
<!--                    <template #header>-->
<!--                      <a-tag color='pink'>pink</a-tag>-->
<!--                    </template>-->
<!--                    <template #extra>-->
<!--                      <span>101题</span>-->
<!--                    </template>-->
<!--                  </a-collapse-panel>-->
<!--                  <a-collapse-panel :showArrow="false"   key="2" >-->
<!--                    <template #header>-->
<!--                      <a-tag color='pink'>pink</a-tag>-->
<!--                    </template>-->
<!--                    <template #extra>-->
<!--                      <span>101题</span>-->
<!--                    </template>-->
<!--                  </a-collapse-panel>-->
<!--                  <a-collapse-panel :showArrow="false" key="3"  >-->
<!--                    <template #header>-->
<!--                      <a-tag color='pink'>pink</a-tag>-->
<!--                    </template>-->
<!--                    <template #extra>-->
<!--                      <span>101题</span>-->
<!--                    </template>-->
<!--                  </a-collapse-panel>-->
<!--                </a-collapse>-->
<!--              </a-card>-->
            </a-col>
          </a-row>
          <a-card class="card" size="small" title="热力图" style="width: 100%;margin-bottom: 20px;">
            <heatmap/>
          </a-card>
          <a-card
              style="width: 100%;margin-bottom: 30px"
              :tab-list="panes"
              :active-tab-key="currentTab"
              @tabChange="key => onTabChange(key, 'currentTab')"
          >
            <template #tabBarExtraContent>
              <a @click="gotoArticles">more</a>
            </template>
            <template #extra>
            </template>
            <div v-show="currentTab === 'problem'">
              <a-table
                  :showHeader="false"
                  :pagination="false"
                  :loading="recentlyACProblemLoading"
                  :columns="recentlyACProblemColumns"
                  :data-source="recentlyACProblems">
                <template #bodyCell="{ column, text ,record}">
                  <template v-if="column.dataIndex === 'title'">
                    <a-tooltip placement="top">
                      <template #title>
                         {{text}}
                      </template>
                      <a @click="gotoProblem(record)">{{record.problemId}} . {{text}}</a>
                    </a-tooltip>
                  </template>
                </template>
              </a-table>
            </div>

            <div v-show="currentTab == 'article'">
              <a-table
                  :showHeader="false"
                  :pagination="false"
                  :loading="articlesLoading"
                  :columns="articleColumns"
                  :data-source="articles">
                <template #bodyCell="{ column, text ,record}">
                  <template v-if="column.dataIndex === 'articleTitle'">
                    <a-tooltip placement="top">
                      <template #title>
                        {{text}}
                      </template>
                      <a @click="() => router.push(`/article/${record.id}`)">#{{record.type?.name}}. {{text}}</a>
                    </a-tooltip>
                  </template>
                  <template v-if="column.dataIndex === 'createTime'">
                    <span>
                       <span  style="cursor: pointer">
                      <component  :is="StarOutlined" />
                      {{ record.collectionNum || 0 }}
                    </span>
                    <span  style="cursor: pointer;margin: 0 10px">
                      <component  style=";"   :is="LikeOutlined"  />
                      {{ record.thumbsNum || 0 }}
                    </span>
                    <span style="margin-right: 10px">
                      <component :is="MessageOutlined"  />
                      {{ record.articleCommentNum || 0 }}
                    </span>
                    </span>
                    {{text}}
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <a-modal v-model:open="openUpdateUserInfo" title="修改信息" :confirm-loading="confirmLoading" @ok="submitUserInfo">

      <a-form :model="useInfoForm"
              :label-col="labelCol"
              :rules="rules"
              ref="useInfoFormRef"
      >
        <a-form-item label="头像" name="avatar">
          <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :max-count="1"
              :show-upload-list="false"
              :action="upload"
              :before-upload="beforeUpload"
              @change="handleChange"
          >
            <a-avatar :size="100" v-if="useInfoForm.avatar" :src="useInfoForm.avatar" />
            <div v-else>
              <loading-outlined v-if="uploading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传头像</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="昵称" name="nickName">
          <a-input  v-model:value="useInfoForm.nickName" />
        </a-form-item>
        <a-form-item label="性别">
          <a-radio-group v-model:value="useInfoForm.sex">
            <a-radio value="0">男</a-radio>
            <a-radio value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="个性签名" name="sign">
          <a-textarea v-model:value="useInfoForm.sign" />
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script lang="ts" setup>

import {
  SettingOutlined,
  EditOutlined,
  LogoutOutlined,
  StarOutlined,
  LikeOutlined,
  MessageOutlined
} from '@ant-design/icons-vue';
import {qinUpload} from "@/utils/uploadUtils"
import * as userApi from "@/api/user"
import {getArticle, getArticleInfo, getRecentlyArticle} from "@/api/article"
import Heatmap from "@/components/Heatmap/index"
import {ref, UnwrapRef} from "vue";
import {message, UploadChangeParam, UploadProps} from "ant-design-vue";
import useStore from "@/store/index";
import router from "@/router";
import {Rule} from "ant-design-vue/es/form";
onMounted( () => {
  userId.value =  useRoute().params.userId as string
  userApi.getUserInfo(userId.value).then(res => {
    Object.assign(useInfoForm, res.data);
  })

  getArticleInfo(userId.value).then(res => {
    Object.assign(articleInfo, res.data);

  })

  initJudgeInfo();
  initRecentlyACProblems();
  initArticles();
})
//个人卡片
const articleInfo = reactive({
  articleNum: 0,
  fansNum: 0,
  followNum: 0
});
const {user} =  useStore();
const userId = ref<String>('')
const isMe = computed(() => {
  //未登录
  if(user.id == null)
    return false;
  if(userId.value == undefined || userId.value == null || userId.value == '' )
    return true;
  if(user.id == userId.value)
    return true;
  return false;
})
const gotoUpdateUserInfo = async () => {
  // const userInfo = await userApi.getUserInfo();
  // Object.assign(useInfoForm,userInfo.data);
  openUpdateUserInfo.value = true;
}
const gotoLogout = () =>{
  user.LogOut().finally(()=>{
    router.push("/")
  })
}

//修改信息弹窗
const openUpdateUserInfo = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const useInfoFormRef = ref()
const submitUserInfo = () => {
  useInfoFormRef.value.validate()
      .then(() => {
        confirmLoading.value = true;
        userApi.updateUserInfo(useInfoForm).finally(() => {
          message.info("更新成功,重新登录生效！",2000);
          confirmLoading.value = false;
          openUpdateUserInfo.value = false;
        })
      })
      .catch(error => {
        console.log('error', error);
      });
};
interface FormState {
  nickName: string;
  sex: number;
  sign: string;
  avatar: string;
  background: string;
}
const useInfoForm: UnwrapRef<FormState> = reactive({
  nickName: '',
  sex: 0,
  sign: '',
  avatar: '',
  background: '',
});

const rules: Record<string, Rule[]> = {
  nickName: [
    { required: true, message: '昵称不能为空', trigger: 'change' },
    { min: 2, max: 10, message: '昵称长度为2-10个字符', trigger: 'blur' },
  ],
  sign: [
    { min: 0, max: 100, message: '签名不能超过100个字符', trigger: 'blur' },
  ],
  avatar: [{ required: true, message: '头像不能为空', trigger: 'change' }],
};
const labelCol = { style: { width: '100px' } };
const fileList = ref([]);
const handleChange = (info: UploadChangeParam) => {
  //console.log(info)
};
const uploading = ref<boolean>(false)
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const upload = (file) => {
  console.log("upload")
  // qinUpload("userInfo/",file).then(res=> {
  //   useInfoForm.avatar = res as string
  // }).catch(err => {
  // })
  return new Promise( (resolve, reject) => {
    qinUpload("userInfo/",file).then(res=> {
      useInfoForm.avatar = res as string
      resolve();
    }).catch(err => {
      reject();
    })
  })
}

//判题信息
const initJudgeInfo = () => {
  JudgeInfoLoading.value = true;
  userApi.getJudgeInfo(userId.value).then(res => {
    judgeInfo.value = res.data
    JudgeInfoLoading.value = false;
  })
}
let judgeInfo = ref([])
const JudgeInfoLoading = ref<boolean>(false)
const percent = (a,b) => {
  if(b == 0)
    return 0;
  return ((a/b)*100).toFixed(0)
}
const judgePercent = computed(() => {
  let sum = 0;
  let acNum = 0;
  if(judgeInfo.value){
    judgeInfo.value.forEach(item => {
      sum += item.problemNum;
      acNum += item.acNum;
    })
  }
  if(sum == 0)
    return 0;
  return ((acNum/sum) *100).toFixed(2)
  return 0;
})


const panes = ref<{  tab: string; key: string; closable?: boolean }[]>([
  { tab: '最近通过', key: 'problem' },
  { tab: '讨论发布', key: 'article' },
]);
const key = ref('problem');
const currentTab = ref('problem')
const onTabChange = (value: string, type: string) => {
  //console.log(value, type);
  if (type === 'key') {
    key.value = value;
  } else if (type === 'currentTab') {
    currentTab.value = value;
  }
};
//最近AC题目
const gotoProblem = (e) => {
  router.push(`/problem/${e.id}`);
}
const recentlyACProblemLoading = ref<boolean>(false)
let recentlyACProblems = []
const recentlyACProblemColumns =  [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis:true,
  },
  {
    title: '发布时间',
    dataIndex: 'submitDate',
    key: 'submitDate',
    ellipsis:true,
    responsive: ['md'],
    width:200
  },
]
const initRecentlyACProblems = async () => {
  recentlyACProblemLoading.value = true;
  recentlyACProblems = (await userApi.getRecentlyACProblem(userId.value)).data
  recentlyACProblemLoading.value = false;
}


//文章列表
const gotoArticles = () => {
  const id = userId.value || user.id
  const c = router.resolve(`/articles/${id}`);
  window.open(c.href, "_blank");
}
const articlesLoading = ref<boolean>(false)
let articles = []
const articleColumns =  [
  {
    title: '标题',
    dataIndex: 'articleTitle',
    key: 'articleTitle',
    ellipsis:true,

  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width:300,
    responsive: ['md'],

  },
]
const initArticles = async () => {
  articlesLoading.value = true;
  articles = (await getRecentlyArticle(userId.value)).data.rows
  articlesLoading.value = false;
}



</script>

<style scoped>

</style>
